package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.constants.BaseConstants;
import cn.itsource.ymcc.domain.MessageStation;
import cn.itsource.ymcc.dto.StationMessageSend2MQ;
import cn.itsource.ymcc.exception.GlobleException;
import cn.itsource.ymcc.service.IMessageStationService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;

@Component
@RocketMQMessageListener(consumerGroup = "service-common-stationmessage-consumer",
        topic = BaseConstants.MessageMQ.TOPIC_MESSAGE,
        selectorExpression = BaseConstants.MessageMQ.TAGS_STATION_MESSAGE
)
@Slf4j
public class StationMessageMQConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageStationService messageStationService;

    @Override
    public void onMessage(MessageExt message) {

        try {
            String bodyStr = new String(message.getBody(),"utf-8");
            StationMessageSend2MQ vo = JSON.parseObject(bodyStr, StationMessageSend2MQ.class);
            //用户群发
            vo.getUserIds().forEach(userId->{
                MessageStation messageStation = new MessageStation();
                messageStation.setContent(vo.getContent());
                messageStation.setSendTime(new Date());
                messageStation.setTitle(vo.getTitle());
                messageStation.setUserId(userId);
                messageStation.setIsread(0);
                messageStation.setType(vo.getTypeName());
                messageStationService.insert(messageStation);

                log.info("站内信保存：{}，{}",userId,messageStation.getContent());
            });

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobleException("站内信保存失败");
        }
    }
}
